# _*_ encoding: utf-8 _*_
# __author__ = 'lx'
import json
from argparse import Namespace
import requests
import aiohttp
from urllib.parse import urlencode


class YoutubeManager:
    def __init__(self):
        self.api_key = None
        self.APIs = {
            'videos': 'https://www.googleapis.com/youtube/v3/videos',
            'search': 'https://www.googleapis.com/youtube/v3/search',
            'channels': 'https://www.googleapis.com/youtube/v3/channels',
            'playlists': 'https://www.googleapis.com/youtube/v3/playlists',
            'playlistItems':
                'https://www.googleapis.com/youtube/v3/playlistItems',
            'commentThreads': 'https://www.googleapis.com/youtube/v3/commentThreads'

        }

    def set_api_key(self, api_key):
        self.api_key = api_key
        return True

    def get_api_key(self):
        return self.api_key

    def get_api(self, apiname):
        return self.APIs[apiname]

    def json_to_object_or_dict(self, json_data,flag='dict'):
        if flag=='dict':
            x = json.loads(json_data)
        else:
            x = json.loads(json_data, object_hook=lambda d: Namespace(**d))
        return x

    def api_request(self, url, parameters):
        parameters['key'] = self.api_key

        req_url = url + '?' + urlencode(parameters)

        response = requests.get(req_url)
        data = response.text

        youtube_object = self.json_to_object_or_dict(data)
        return youtube_object

    async def async_request(self, url, parameters):
        parameters['key'] = self.api_key

        req_url = url + '?' + urlencode(parameters)
        async with aiohttp.request('GET', req_url) as response:
            data = await response.json()

        youtube_object = self.json_to_object_or_dict(data)
        return youtube_object